from  flask import (
    Blueprint,
    render_template,
    views,
    request,
    redirect,
    url_for,
    session
)
from .models import CmsUser
from .forms import LoginForm
import config
bp = Blueprint('cms',__name__,url_prefix='/cms')

@bp.route('/',methods=['GET','POST'])
def index():
    if request.method == 'GET':
        return render_template('cms/cms_index.html')
    else:
        return '您这是GET以外的请求'

# request.files 上传文件
# request.args  get请求参数获取
# request.form  post请求

class LoginView(views.MethodView):

    def get(self,message=None):
        return render_template('cms/cms_login.html',message=message)

    def post(self):
        #实例化一个表单对象
        #判断用户是否输入符合要求
        #接收浏览器表单输入内容
        # 验证成功将用户信息保存到session中
        #成功以后跳转
        form = LoginForm(request.form)
        if form.validate(): #
            email = form.email.data
            password = form.password.data
            remember = form.remember.data
            user = CmsUser.query.filter_by(email=email).first()

            if user and user.check_password(password):
                session[config.CMS_USER_ID] = user.id #用户名密码都正确 所以将用户的id存到session中
                if remember:
                    session.permanent = True #如果用户勾选  那么默认过期时间 31天
                return redirect(url_for('cms.index'))
            else:
                return self.get(message='邮箱或者密码错误')
        else:
            return redirect(url_for('cms.login'))
class ResetPasswdView(views.MethodView):
    def get(self):
        return render_template('cms/cms_resetpasswd.html')
bp.add_url_rule('/login/',view_func=LoginView.as_view('login'))
bp.add_url_rule('/resetpasswd/',view_func=ResetPasswdView.as_view('resetpasswd'))